package com.tensquare.article.controller;

import com.tensquare.article.pojo.Comment;
import com.tensquare.article.service.CommentService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    CommentService commentService;

    @Autowired
    RedisTemplate redisTemplate;

    //通过id查询
    @RequestMapping(value = "{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable String id){
        Comment byId = commentService.findById(id);
        return new Result(true, StatusCode.OK,null,byId);
    }

    //查询所有
    @RequestMapping(method = RequestMethod.GET)
    public Result findById(){
        List<Comment> all = commentService.findAll();
        return new Result(true, StatusCode.OK,null,all);
    }

    //添加
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody Comment comment){
        commentService.add(comment);
        return new Result(true, StatusCode.OK,null);
    }

    //删除
    @RequestMapping(value = "{id}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id){
        commentService.delete(id);
        return new Result(true, StatusCode.OK,null);
    }

    //修改
    @RequestMapping(value = "{id}",method = RequestMethod.PUT)
    public Result update(@PathVariable String id,@RequestBody Comment comment){
        commentService.update(id,comment);
        return new Result(true, StatusCode.OK,null);
    }

    //点赞
    @RequestMapping(value = "/thumbup/{id}",method = RequestMethod.PUT)
    public Result addThumbup(@PathVariable String id){
        //获取用户id
        String userId="123";
        //文章+用户id
        String userComment=userId+id;
        //查询reidis
        Object o = redisTemplate.opsForValue().get("_thumbup" + userComment);
        if(o==null){
            //点赞成功
            commentService.addThumbup(id);
            //设置key
            redisTemplate.opsForValue().set("_thumbup" + userComment,"123");
            return new Result(true, StatusCode.OK,"点赞成功");
        }else {
            return new Result(true, StatusCode.OK,"不能重复点赞");
        }
    }
}
